import React from 'react'; 
import { Tree } from 'antd';
const TreeNode = Tree.TreeNode;

class TreeComp extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      expandedKeys: this.props.expandedKeys || [],
      autoExpandParent: true,
      checkedKeys: this.props.checkedKeys || [],
      selectedKeys: this.props.selectedKeys || [],
      treeData:this.props.treeData
    }
  }

  // 通过父组件更新子组件props时触发
  componentWillReceiveProps(nextProps) { 
    this.setState({
      treeData:nextProps.treeData,
      checkedKeys:nextProps.checkedKeys,
      selectedKeys:nextProps.selectedKeys
    })
  }

  onExpand = (expandedKeys) => {
    // console.log('onExpand', arguments);
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }

  onCheck = (checkedKeys,info) => {
    this.setState({ checkedKeys });
    //保留上一级
    this.props.getCheckedValue([...checkedKeys,...info.halfCheckedKeys]);
  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });
  }

  render() {
    return (
      <Tree
        checkable
        onExpand={this.onExpand}
        expandedKeys={this.state.expandedKeys}
        autoExpandParent={this.state.autoExpandParent}
        onCheck={this.onCheck}
        checkedKeys={this.state.checkedKeys}
        onSelect={this.onSelect}
        selectedKeys={this.state.selectedKeys}
      >
        {this.renderTreeNodes(this.state.treeData)}
      </Tree>
    );
  }
}

export default TreeComp